package com.qy.controller.app;

import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.model.Member;
import com.qy.model.Message;
import com.qy.model.Withdraw;
import com.qy.service.MemberService;
import com.qy.service.MessageService;
import com.qy.service.WithdrawService;
import com.github.pagehelper.PageHelper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController
@RequestMapping("app/withdraw")
public class WithdrawController {
    @Resource
    private WithdrawService withdrawService;

    @Resource
    private MemberService memberService;

    @Resource
    private MessageService messageService;

    @PostMapping("/add")
    public Result add(@RequestBody Withdraw withdraw) {
        withdrawService.save(withdraw);
        return ResultGenerator.successResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        withdrawService.deleteById(id);
        return ResultGenerator.successResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Withdraw withdraw) {
        withdrawService.update(withdraw);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Withdraw withdraw = withdrawService.findById(id);
        return ResultGenerator.successResult(withdraw);
    }

    @GetMapping("/list")
    public Result list(PageBean<Withdraw> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Withdraw> list = withdrawService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //提现
    @PostMapping("/withdraw")
    public Result withdraw(@RequestBody Withdraw withdraw) {
        if (withdraw.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        if (withdraw.getApply_amount() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        Member member = memberService.findById(withdraw.getUser_id());
        member.setBalance(String.valueOf(Double.valueOf(member.getBalance()) - Double.valueOf(withdraw.getApply_amount())));
        memberService.update(member);
        withdraw.setPhone(member.getPhone());
        withdraw.setApplicant(member.getName());
        withdraw.setCard_holder(member.getCard_holder());
        withdraw.setAdd_time(DateUtil.getNowTimestamp());
        withdrawService.save(withdraw);

        Message message = new Message();
        message.setMessage_type(1);
        message.setMessage_content(member.getNickname() + "发起了提现申请");
        message.setMessage_port(2);
        message.setAdd_time(DateUtil.getNowTimestamp());
        messageService.save(message);

        return ResultGenerator.successResult();
    }
}
